package com.ds.infrastructure.hyperspace.container.internal.operator;

import com.ds.infrastructure.hyperspace.common.Operator;

/**
 * usage eg:
 * [DELIMITER_SUB_STRING, delimiter, delimiter hit index from 1]
 *
 * @author  Weishaoying
 */
public class DelimiterSubStringOperator implements Operator {

    private static final int AGRS_LENGTH = 2;

    @Override
    public String compute(String inputValue, String[] args) {
        if (inputValue == null) {
            return null;
        }
        String delimiterStr = args[0];
        int delimiterHitIndex = Integer.parseInt(args[1]);

        int tempStartIndex = 0;
        int temHitIndex = 0;
        int tempDelimiterStartIndex = 0;
        while (tempDelimiterStartIndex < inputValue.length()) {
            tempDelimiterStartIndex = inputValue.indexOf(delimiterStr, tempDelimiterStartIndex);
            if (tempDelimiterStartIndex == -1) {
                break;
            }
            tempStartIndex = ++tempDelimiterStartIndex;
            if (++temHitIndex == delimiterHitIndex) {
                break;
            }
        }

        if (temHitIndex != delimiterHitIndex || tempStartIndex >= inputValue.length()) {
            return null;
        }

        int tempEndIndex = inputValue.indexOf(delimiterStr, tempStartIndex);
        if (tempEndIndex == -1) {
            tempEndIndex = inputValue.length();
        }
        return inputValue.substring(tempStartIndex, tempEndIndex);
    }

    @Override
    public String getOperatorName() {
        return "DELIMITER_SUB_STRING";
    }

    @Override
    public int getOperatorArgsLength() {
        return AGRS_LENGTH;
    }
}
